import { useEffect, useMemo, useRef, useState } from "react";
import { Checkbox, Tooltip, Button, message } from "antd";
import { IUser } from "@/store/user";
import { useMove } from "@/hooks/useMove";
import { useTimer } from "@/hooks/useTimer";
import { Avatar } from "@/components/Avatar";
import { AvatarPlayer } from "../AvatarPlayer";
import { RoomDetail } from "@/apis/chatroom";
import { PhoneStatus } from "./interface";
import { useUserStore } from "@/store/user";

interface PhoneProps {
  room: RoomDetail;
  type: "video" | "audio";
  callerId?: number;
  calleeIds?: number[];
  status?: PhoneStatus;
  localStream?: MediaStream | null;
  remoteStreamRefs?: React.MutableRefObject<Map<number, MediaStream> | null>;
  onCall: (calleeIds: number[]) => void; // 呼叫
  onStatus: (status: PhoneStatus) => void;
  onAccept: () => void; // 接听
  onHangUp: () => void; // 挂断
}
export function Phone(props: PhoneProps) {
  const {
    room,
    type,
    callerId,
    calleeIds,
    status = PhoneStatus.HangUp,
    localStream,
    remoteStreamRefs,
    onStatus,
    onAccept,
    onHangUp,
    onCall,
  } = props;
  const { users, chatType } = room;
  const { userInfo } = useUserStore();
  const phoneRef = useRef<HTMLDivElement>(null);
  const audioRef = useRef<HTMLAudioElement>(null);
  const localVideoRef = useRef<HTMLVideoElement>(null);

  const { isMoving } = useMove(phoneRef);
  const { formatTime, start, reset } = useTimer();

  const [selectedUsers, setSelectedUsers] = useState<IUser[]>([]);

  // 呼叫
  const handleCall = () => {
    if (selectedUsers.length < 1) return message.info("请选择联系人");
    const selectedUserIds = selectedUsers.map((user) => user.id);
    onCall(selectedUserIds);
  };

  const isCaller = useMemo(() => {
    return callerId === userInfo?.id;
  }, [callerId, userInfo]);

  const calleeUsers = useMemo(() => {
    if (calleeIds) {
      return users.filter((user) => calleeIds.includes(user.id));
    }
    return [];
  }, [calleeIds]);

  useEffect(() => {
    if (localStream && localVideoRef.current) {
      localVideoRef.current.srcObject = localStream;
    }
  }, [localStream]);

  // 通话计时器
  useEffect(() => {
    if (status === PhoneStatus.Chating) {
      start();
    } else {
      reset();
    }
    return () => {
      reset(); // 清除定时器
    };
  }, [status]);

  // 来电铃声
  useEffect(() => {
    if (!audioRef.current) return;
    const audio = audioRef.current;
    if (status === PhoneStatus.Calling) {
      if (audio.paused) {
        audio.play();
      }
    } else {
      if (!audio.paused) {
        audio.pause();
      }
    }
    return () => {
      if (audio && !audio.paused) {
        audio.pause();
      }
    };
  }, [status]);

  return (
    status !== PhoneStatus.HangUp &&
    userInfo && (
      <div className="mask fixed top-0 left-0 w-full h-full bg-black/50 z-[99]">
        <div
          ref={phoneRef}
          className="flex flex-col phone cursor-pointer overflow-hidden border-2 border-slate-200 fixed left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 z-[100] w-[280px] h-[530px] bg-[#1f212c] rounded-xl "
        >
          {/* 单聊显示内容 */}
          {chatType === "Private" && (
            <div className="relative main-video w-full h-full">
              <video
                className="w-full h-full object-cover rounded-none"
                ref={localVideoRef}
                autoPlay
                playsInline
              ></video>
            </div>
          )}
          {/* 打开状态：呼叫方且是群聊 */}
          {status === PhoneStatus.Open && isCaller && chatType === "Group" && (
            <div className="flex flex-col justify-evenly p-4 h-full ">
              <div className="flex gap-1 justify-center h-[40px] overflow-y-scroll  scrollbar-custom ">
                <Avatar src={userInfo.avatar} />
                {selectedUsers.map((user) => {
                  return (
                    <Avatar
                      key={user.id}
                      src={user.avatar}
                      className=" text-white flex items-center justify-center line-clamp-1"
                    />
                  );
                })}
              </div>
              <div className="flex-1 my-4 overflow-y-scroll scrollbar-custom h-[200px]">
                <Checkbox.Group
                  onChange={setSelectedUsers}
                  className="py-2 w-full scrollbar-custom"
                >
                  {users.map((user) => {
                    return (
                      <Checkbox
                        key={user.id}
                        disabled={user.id === userInfo.id}
                        value={user}
                        className={`w-full flex items-center p-2 my-2 gap-2 bg-[#2D323F] hover:bg-[#1D90F5] hover:shadow-[3px_2px_10px_0px_rgb(0,136,255)] transition-all duration-200 rounded-lg ${
                          user.id === userInfo.id
                            ? "opacity-50 hover:bg-[#2D323F] hover:shadow-none"
                            : ""
                        }`}
                      >
                        <Avatar
                          name={user.nickName}
                          src={user.avatar}
                          className="text-white flex items-center justify-center line-clamp-1"
                        />
                      </Checkbox>
                    );
                  })}
                </Checkbox.Group>
              </div>
              <div className="flex justify-between mr-2">
                <Button
                  className="h-[40px] bg-[#1D90F5]"
                  type="primary"
                  disabled={selectedUsers.length < 1}
                  onClick={handleCall}
                >
                  确定
                </Button>
                <Button
                  className="h-[40px]"
                  type="link"
                  onClick={() => onStatus(PhoneStatus.HangUp)}
                >
                  返回
                </Button>
              </div>
            </div>
          )}

          {/* 呼叫状态和通知状态 */}
          {(status === PhoneStatus.Calling ||
            status === PhoneStatus.Chating) && (
            <div className="flex flex-col  absolute top-0 left-0 w-full h-full bg-black/0 ">
              {/* 顶部工具区 */}
              <div className="phone-header flex items-center justify-between p-2 px-4">
                <Tooltip title="最小化窗口">
                  <span className="iconfont icon-chuangkouzuixiaohua-filled text-[#979DA7] hover:text-[#d9e3f5] transition-all duration-200"></span>
                </Tooltip>
              </div>
              {/* 主体内容区 */}
              <div className="relative phone-body flex-1 flex flex-col items-center justify-evenly">
                {/* 头像展示区 */}
                <div className="flex-1 flex flex-wrap gap-4 items-center justify-center">
                  {
                    // 只有处于呼叫状态且是被呼叫方，才显示这个
                    status === PhoneStatus.Calling && !isCaller ? (
                      <>
                        <AvatarPlayer
                          userInfo={users.find((user) => user.id === callerId)}
                          type={type}
                          loading={false}
                        />
                        {chatType === "Group" && calleeUsers.length >= 1 && (
                          <div className="w-full text-center ">
                            <span className="text-gray-400 text-sm">
                              参与通话的还有
                            </span>
                            <div className="flex justify-center gap-2 mt-2">
                              {calleeUsers.map((user) => {
                                return (
                                  <AvatarPlayer
                                    key={user.id}
                                    userInfo={user}
                                    type={type}
                                    loading={false}
                                    className="zoom-sm"
                                  />
                                );
                              })}
                            </div>
                          </div>
                        )}
                      </>
                    ) : (
                      <>
                        {/* 如果不是呼叫方，还要显示呼叫方头像 */}
                        {!isCaller && callerId && (
                          <AvatarPlayer
                            mediaStream={remoteStreamRefs?.current?.get(
                              callerId
                            )}
                            userInfo={users.find(
                              (user) => user.id === callerId
                            )}
                            type={type}
                          />
                        )}

                        {/* 显示自身 */}
                        {chatType === "Group" && (
                          <>
                            {calleeUsers?.map((user) => {
                              return (
                                <div
                                  key={user.id}
                                  className="w-[100px] h-[100px] overflow-hidden p-[2px] object-cover"
                                >
                                  <AvatarPlayer
                                    mediaStream={
                                      remoteStreamRefs &&
                                      remoteStreamRefs?.current?.get(user.id)
                                    }
                                    userInfo={user}
                                    type={type}
                                  />
                                </div>
                              );
                            })}
                            <AvatarPlayer
                              mediaStream={localStream}
                              userInfo={userInfo}
                              type={type}
                            />
                          </>
                        )}
                      </>
                    )
                  }
                </div>

                {/* 来电文字 */}
                <div className="flex-1 flex items-end text-sm text-gray-400">
                  {/* 通话状态 */}
                  {status === PhoneStatus.Chating ? (
                    <div className="text-gray-400">{formatTime}</div>
                  ) : isCaller ? (
                    // 呼叫状态: 呼叫方
                    <div className="flex">
                      等待对方接受
                      <div className="flex space-x-1 ml-1">
                        <span className="animate-blink delay-0">.</span>
                        <span className="animate-blink delay-200">.</span>
                        <span className="animate-blink delay-400">.</span>
                      </div>
                    </div>
                  ) : (
                    // 呼叫状态：被呼叫方
                    <div>{`邀请您${chatType === "Group" ? "加入" : "进行"}${
                      type === "video" ? "视频" : "语音"
                    }通话`}</div>
                  )}
                </div>
              </div>

              {/* 按钮区 */}
              <div className="phone-footer h-[100px] flex items-center justify-evenly p-2">
                {/* 接听按钮：只有在被呼叫方且处于呼叫状态才有 */}
                {!isCaller && status === PhoneStatus.Calling && (
                  <Tooltip title="接听">
                    <span
                      className="w-[50px] h-[50px] !text-[50px] animate-breath !leading-none iconfont icon-jieting text-[#49DB62] bg-white rounded-full"
                      onClick={onAccept}
                    ></span>
                  </Tooltip>
                )}
                <Tooltip title="挂断">
                  <span
                    className="w-[50px] h-[50px] !text-[50px] animate-breath !leading-none iconfont icon-guaduan text-[#f10] hover:text-[#FF3E3E]  bg-white rounded-full"
                    onClick={onHangUp}
                  ></span>
                </Tooltip>
              </div>
            </div>
          )}
        </div>
        <div className="tools">
          {/* 来电语音 */}
          <audio
            ref={audioRef}
            src="/audio/phone.mp3"
            hidden
            loop
            muted
          ></audio>
        </div>
      </div>
    )
  );
}
